package com.stx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
//import com.stx.common.Rank;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.common.PageValue;
import com.stx.common.Result;
import com.stx.pojo.Match;
import com.stx.pojo.Player;
import com.stx.pojo.Ruanyue;
import com.stx.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@Tag(name = "参赛表相关接口")
@RequestMapping("/match")
public class MatchController {

    @Autowired
    private MatchService matchService;
    @Autowired
    private PlayerService playerService;

    @Autowired
    private RuanyueService ruanyueService;
    @Autowired
    private IMatchService jmatchService;
    @Autowired
    private IPlayerService jplayerService;

    private static final Logger logger = LogManager.getLogger(MatchController.class);

    @Operation(
            summary = "列表",
            description = "参赛列表",
            tags = {"参赛表相关接口"}
    )
    @PostMapping("/list")
    public Result getmatch(@RequestBody Match matchId) {
        LambdaQueryWrapper<Match> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Match::getRuaId, matchId.getRuaId());
        wrapper.orderByAsc(Match::getMatSequence);
        List<Match> matchList = jmatchService.getBaseMapper().selectList(wrapper);
        logger.info(matchList);
        //List<Match> matchList = jmatchService.list();
        List<Player> playerList = jplayerService.list();
        for (Match match : matchList) {
            for (Player player : playerList) {
                if (match.getMatName().equals(player.getPlaName())) {
                    match.setAvatar(player.getPlaAvatar());
                    match.setPlaDepartment(player.getPlaDepartment());
                    match.setPlagender(player.getPlaGender());
                }
            }
        }
        //按照顺序由小到大排序
        /*matchList.sort(new Comparator<Match>() {
            @Override
            public int compare(Match o1, Match o2) {
                if (o1.getMatSequence() == null || o2.getMatSequence() == null){
                    return 0;
                }
                Integer m = Integer.parseInt(o1.getMatSequence());
                Integer n = Integer.parseInt(o2.getMatSequence());
                return m.compareTo(n);
            }
        });*/
        matchList.get(0).setTotal(matchList.size());
        return Result.success(matchList);
    }

    @Operation(
            summary = "添加/修改接口",
            description = "参赛添加和修改列表",
            tags = {"参赛表相关接口"}
    )
    @PostMapping("/save")
    public Result save(@RequestBody Match match) {
        match.setMatDate(LocalDateTime.now());
        jmatchService.saveOrUpdate(match);
        return Result.success();
    }

    @Operation(
            summary = "删除接口",
            description = "参赛删除接口，根据id删除",
            tags = {"参赛表相关接口"}
    )
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        matchService.removeById(id);
        return Result.success();
    }

    @Operation(
            summary = "分页",
            description = "参赛分页查询",
            tags = {"参赛表相关接口"}
    )
    @PostMapping("/page")
    public Result findPage(@RequestBody PageValue pageValue) {
        if (pageValue.getCurrentPage() != 0 && pageValue.getPageSize() !=0) {
            Page<Match> page = matchService.find(pageValue.getUserName(),pageValue.getCurrentPage(),pageValue.getPageSize());
            return Result.success(page);
        } else {
            List<Match> list = matchService.getmatch();
            return Result.success(list);
        }
    }

    @Operation(
            summary = "保存分数",
            description = "保存分数",
            tags = {"参赛表相关接口"}

    )
    @PostMapping("/savescore")
    public Result savesocre(@RequestBody Match match) {
        Integer id = match.getId();
        Double matScore = match.getMatScore();
        match.setMatDate(LocalDateTime.now());
        UpdateWrapper<Match> updateWrapper = new UpdateWrapper<>();
        //设置更新的条件
        updateWrapper.eq("id",id);
        //设置要更新的字段
        updateWrapper.set("mat_score",matScore);
        boolean success = jmatchService.update(updateWrapper);
        logger.info("选手最后总分：id：" + id + "  matScore：" + matScore);
        if (success) {
            return Result.success();
        } else {
            return Result.error("更新失败");
        }
    }

    @Operation(
            summary = "评委端首页",
            description = "评委端的首页",
            tags = {"参赛表相关接口"}
    )
    @PostMapping("/players")
    public Result listByRuanyueId() {
        Ruanyue last = ruanyueService.last();
        List<Match> matches = matchService.listByRuanyueId(last.getId());
        List<Player> list = playerService.list();
        Map<Integer, Player> collect = list.stream().collect(Collectors.toMap(Player::getId, player -> player));
        for (Match match : matches) {
            Player player = collect.get(match.getPlaId());
            match.setAvatar(Objects.isNull(player) ? "" : player.getPlaAvatar());
            match.setPlaDepartment(Objects.isNull(player) ? "" : player.getPlaDepartment());
        }
        return Result.success(matches);
    }

    @Operation(
        summary = "更新序号",
        description = "更新材料序号接口",
        tags = {"参赛表相关接口"}
)
@PostMapping("/updateSequence")
public Result updateSequence(@RequestBody Map<String, Object> requestBody) {
    Integer id = (Integer) requestBody.get("id");
    Integer matSequence = (Integer) requestBody.get("matSequence");

    // 这里可以进行验证，例如检查id是否存在
        Match judge = matchService.getById(id);
    if (judge == null) {
        return Result.error("指定的记录不存在");
    }

    // 更新序号的逻辑
    judge.setMatSequence(matSequence); // 假设Judge类中有matSequence字段
    boolean updateResult = matchService.updateById(judge);

    if (updateResult) {
        return Result.success();
    } else {
        return Result.error("序号更新失败");
    }
}

    /*@GetMapping("/excel")
    public Result excelTest(){
        //定义文件位置
        String fileName = "C:\\Users\\yandaibo\\Desktop\\test\\easyexcel.xlsx";
        System.out.println("文件位置：" + fileName);
        //读取表格文件
        EasyExcel.read(fileName, Match.class,new PageReadListener<Match>(matchList -> {
            matchList.forEach(match -> {
                logger.info(match.toString());
            });
            jmatchService.saveBatch(matchList);
        })).sheet().doRead();
        return Result.success();
    }*/

    /*@PostMapping("/excel")
    public Result uploadExcel(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("File is empty");
            }
            //建立文件夹
            File fileExcel = new File("C:\\Users\\yandaibo\\Desktop\\test");
            if (!fileExcel.exists()){
                fileExcel.mkdirs();
            }
            // 文件处理成功
            String fileName = file.getOriginalFilename();
            //File.separator用来代替\\提高文件的跨平台可用
            String fileAddress = fileExcel + File.separator + fileName;
            file.transferTo(new File(fileAddress));
            logger.info("文件位置：" + fileAddress);
            EasyExcel.read(fileAddress, Match.class,new PageReadListener<Match>(matchList -> {
                matchList.forEach(match -> {
                    logger.info(match.toString());
                });
                for (Match match : matchList) {
                    match.setMatDate(LocalDateTime.now());
                }
                boolean b = jmatchService.saveBatch(matchList);
                logger.info("批量插入结果：" + b);
            })).sheet().doRead();
            return Result.success("File uploaded successfully" + HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("File upload failed" + HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }*/
}
